module.exports = class userService {
  static async login(username, password, type) {
    const User = require("../model/user")();
    if (!type) {
      return await User.where({
        username,
        password,
      }).select();
    } else {
      return await User.where({
        username,
        password,
        type,
      }).select();
    }
  }

  static async register(username, password) {
    const User = require("../model/user")();
    return await User.insert({
      username,
      password,
      type: "user",
      avatar: "",
    });
  }
  //修改密码
  static async updatePassword(uid, password, repassword) {
    const User = require("../model/user")();
    return await User.where({
      uid,
      password,
    }).update({ password: repassword });
  }

  static async updateAvatar(uid, avatar) {
    const User = require("../model/user")();
    return await User.where({
      uid,
    }).update({ avatar });
  }

  static async getUserData(page) {
    const User = require("../model/user")();
    return await User.order("uid", "DESC")
      .limit((page - 1) * 10, page * 10)
      .select();
  }
  static async getSum() {
    const User = require("../model/user")();
    return await User.count();
  }

  static async batchAddUser(data) {
    const User = require("../model/user")();
    return await User.insertAll(data);
  }
  static async batchUpdateUser(data) {
    const User = require("../model/user")();

    let uids = data.map((item) => item.uid);
    let usernameArr = data.map((item) => item.username);
    let passwordArr = data.map((item) => item.password);
    let typeArr = data.map((item) => item.type);

    for (let i = 0; i < data.length; i++) {
      await User.where({
        uid: uids[i],
      }).update({
        type: typeArr[i],
        username: usernameArr[i],
        password: passwordArr[i],
      });
    }
    return true;
  }

  static async batchDeteleUser(data) {
    const User = require("../model/user")();

    let uids = data.map((item) => item.uid);

    for (let i = 0; i < data.length; i++) {
      await User.where({
        uid: uids[i],
      }).del();
    }
    return true;
  }
};
